package cn.edu.dgut.css.sai.dgutoauth2.web;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 测试用控制器
 *
 * @author Sai
 * @since 1.0
 */
@Controller
public class OAuth2LoginController {

    @GetMapping("/user")
    public String getUser(Model model,
                          @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                          @AuthenticationPrincipal OAuth2User oauth2User) {
        model.addAttribute("userName", oauth2User.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("accessToken", authorizedClient.getAccessToken().getTokenType());
        model.addAttribute("userAuthorities", oauth2User.getAuthorities());
        model.addAttribute("userAttributes", oauth2User.getAttributes());

        return "user";
    }

    @GetMapping("/submit")
    public String submit(Model model,

                          @AuthenticationPrincipal OAuth2User oauth2User) {
        model.addAttribute("name", oauth2User.getAttributes().get("name"));
        model.addAttribute("uid", oauth2User.getAttributes().get("username"));
        return "submit";
    }
}
